package topic;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import common.ContantsConfig;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.Connection;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;

import java.io.IOException;

/**
 * Created by Will.Zhang on 2017/2/16 0016 17:30.
 */
public class TopicConsumer {

    public static void main(String[] args) throws IOException {

        String username = ContantsConfig.USER;
        String password = ContantsConfig.PASSWORD;

        String exchangeName = "alters";

        String criticalQueueName = "critical";
        String criticalRoutingKey = "critical.*";

        String rateLimitQueueName = "rate_limit";
        String rateLimitRoutingKey = "*.rate_limit";

        //端口默认使用5672
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory(ContantsConfig.MQ_HOST);
        connectionFactory.setUsername(username);
        connectionFactory.setPassword(password);

        Connection connection = connectionFactory.createConnection();
        Channel channel = connection.createChannel(false);

        /**
         * 声明交换器  生产者和消费者只需要一个声明exchange的类型。也可以两个都声明
         */
        channel.exchangeDeclare(exchangeName, BuiltinExchangeType.TOPIC, true, false, null);


        //声明队列(routing-key为critical.*)这个队列只会接收routing-key=critical.开头的消息
        channel.queueDeclare(criticalQueueName, false, true, false, null);
        channel.queueBind(criticalQueueName, exchangeName, criticalRoutingKey);

        //声明队列(routing-key为*.rate_limit)这个队列只会接收routing-key=.rate_limit结尾的消息
        channel.queueDeclare(rateLimitQueueName, false, true, false, null);
        channel.queueBind(rateLimitQueueName, exchangeName, rateLimitRoutingKey);


        //使用监听异步接收消息,为了方便展示,所以分开写
        SimpleMessageListenerContainer criticalContainer = new SimpleMessageListenerContainer(connectionFactory);
        criticalContainer.setQueueNames(criticalQueueName);
        criticalContainer.setMessageListener(new MessageListener() {
            public void onMessage(Message message) {
                System.out.println("critical:" + new String(message.getBody()));
            }
        });
        criticalContainer.start();



        SimpleMessageListenerContainer rateLimitContainer = new SimpleMessageListenerContainer(connectionFactory);
        rateLimitContainer.setQueueNames(rateLimitQueueName);
        rateLimitContainer.setMessageListener(new MessageListener() {
            public void onMessage(Message message) {
                System.out.println("rate_limit:" + new String(message.getBody()));
            }
        });


        rateLimitContainer.start();
    }
}
